/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* merge(ListNode* list1, ListNode* list2) {
        // 将两个有序链表连接起来
        ListNode* newnode = new ListNode(0, nullptr);
        ListNode* node = newnode;
        ListNode* tmp1 = list1;
        ListNode* tmp2 = list2;
        while (tmp1 != nullptr && tmp2 != nullptr) {
            if (tmp1->val < tmp2->val) {
                node->next = tmp1;
                tmp1 = tmp1->next;
            } else {
                node->next = tmp2;
                tmp2 = tmp2->next;
            }
            node = node->next;
        }
        if (tmp1 != nullptr) {
            node->next = tmp1;
        } else if (tmp2 != nullptr) {
            node->next = tmp2;
        }
        return newnode->next;
    }
    ListNode* mergesort(vector<ListNode*>& lists, int left, int right) {
        if (left > right) {
            return nullptr;
        }
        else if(left == right)
        {
            return lists[left];
        }
        int mid = (left + right) >> 1;
        return merge(mergesort(lists, left, mid),
                     mergesort(lists, mid + 1, right));
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        // 继续采用分治的思想，让数组中的链表两两结合生成新的链表并以此循环
        return mergesort(lists, 0, lists.size() - 1);
    }
};